package com.wz.jiangsu.main.subscrible;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;

public class SimpleHttpServer {

    public static void main(String[] args) throws IOException {
        // 创建一个 HTTP 服务器，监听指定的端口
        HttpServer server = HttpServer.create(new InetSocketAddress(8082), 0);

        // 创建处理请求的处理器
        server.createContext("/", new RequestHandler());

        // 启动服务器
        server.start();
        System.out.println("Server started on port 8082");
    }

    // 定义处理请求的处理器
    static class RequestHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            // 获取请求的方法和 URI
            String method = exchange.getRequestMethod();
            String requestURI = exchange.getRequestURI().toString();

            // 输出请求的信息
            System.out.println("Received request:");
            System.out.println("Method: " + method);
            System.out.println("Request URI: " + requestURI);

            // 读取请求的正文
            StringBuilder requestBody = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(exchange.getRequestBody()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    requestBody.append(line);
                }
            }

            // 输出请求正文
            System.out.println("Request Body: " + requestBody.toString());

            // 响应客户端
            String response = "Request received";
            exchange.sendResponseHeaders(200, response.getBytes().length);
            try (OutputStream os = exchange.getResponseBody()) {
                os.write(response.getBytes());
            }
        }
    }
}
